const { user, message, content } = require("../models");
let auth = require("../utils/auth");

//访问登录界面get请求
let login_fn = async (ctx, next) => {

   await ctx.render('login');

}

let register_fn = async (ctx, next) => {
   await ctx.render("register.html");
}

//提交登录post请求
let loginDone_fn = async (ctx, next) => {
   let username = ctx.request.body.username;
   let password = ctx.request.body.password;
   console.log(username);
   console.log(password);
   let result2 = '';

   if (username.length > 0 && password.length > 0) {
      let u3 = await user.findOne({
         where: {
            username: username,
            password: password
         }
      }).then((row) => {
         //字符串
         let user = JSON.stringify(row);
         console.log(user);
         //转换为object 
         let userid = JSON.parse(user);
         console.log(userid);
         //数据库中已经注册了该用户
         if (user !== "null") {
            result2 = { resultCode: 200, msg: "登录成功" };
            ctx.session.username = username;
            ctx.session.userid = row.id;
         } else {
            result2 = { resultCode: 1000, msg: "登陆失败" }
         }
      })

   }
   ctx.body = JSON.stringify(result2);
}


//提交注册post请求
let registerDone_fn = async (ctx, next) => {
   let username = ctx.request.body.username;
   let password = ctx.request.body.password;
   let againpassword = ctx.request.body.againpassword;
   console.log(username);
   console.log(password);
   console.log(againpassword);

   if (username.length > 0 && password.length > 0 && password === againpassword) {
      let u1 = await user.findOne({
         where: { username: username }

      });
      console.log(u1);
      console.log(JSON.stringify(u1));
      let result = '';
      //当user不为空时表示里面有这条数据
      if (u1) {
         result = { resultCode: 1000, msg: "注册失败" };
      } else {
         let u2 = user.create({
            username: username,
            password: password
         });
         result = { resultCode: 200, msg: "注册成功" };
         //  await ctx.render("login");
         // ctx.redirect("login");
      }
      ctx.body = result;


   }
   else {
      console.log("用户名或者密码不能为空 并且两次密码相同")
   }

}

//首页
let homepage_fn = async (ctx, next) => {

   let username = ctx.session.username;
   //查询说说表所有信息
   let msgs = JSON.parse(JSON.stringify(await message.findAll({
      order: [
         ["id", "desc"]
      ]
   }
   )));
   //查询评论表所有信息
   let comts = JSON.parse(JSON.stringify(await content.findAll()));
   let userIds = [];


   // 谁对谁说功能 第一步查找到msg中所有的fromUserId
   msgs.forEach(row => {
      userIds.push(row.fromuserId);
   });

   //谁对谁说功能 第二步查找到comts中所有的fromUserId
   comts.forEach(row => {
      userIds.push(row.fromuserId);
   });

   //谁对谁说功能 第三步查根据找查到的用户Id，查找用户表中的用户信息

   let userAll = await user.findAll({
      where: {
         id: userIds
      }
   })// select * from users where id in (1,2,3,4)

   // console.log(userAll,"查看用户表的信息"); 
   // console.log(comts,"查看评论表");

   comts.forEach(row => {
      let currentUser = userAll.filter(user => {
         return row.fromuserId === user.id;
      })[0];
      row.comUserName = currentUser.username;
      console.log(currentUser);
      console.log(row.comUserName);
   });


   // 将说说和评论根据msgId按需要组合，将相应的评论挂载在对应的说说上
   msgs.forEach(msg => {
      let msgComment = comts.filter(item => {
         return item.touserId === msg.id;
      });
      let currentUser = userAll.filter(row => {
         return row.id === msg.fromuserId;
      })[0];
      msg.msgUserName = currentUser.username;
      msg.comments = msgComment;
   });

   console.log(msgs);
   let obj = {
      admin: username,
      msgs: msgs
   };
   await ctx.render("index", obj);

}


//注销登录
let logout_fn = async (ctx, next) => {
   ctx.session.username = "";
   await ctx.redirect("/login")
}

//发表说说
let say_fn = async (ctx, next) => {
   let msgSay = ctx.request.body.msgSay || '';
   let userId = ctx.session.userid;
   let msg = await message.create({
      fromuserId: userId,
      content: msgSay
   })
   let data = JSON.stringify(msg);

   console.log(msgSay);

   ctx.body = { code: 200, data, msg: "发表说说成功" };
}


//吐槽
let comment_fn = async (ctx, next) => {
   let comment = ctx.request.body.content || '';
   let touserId = ctx.request.body.touserId || '';
   let userId = ctx.session.userid;
   let msg1 = await content.create({
      fromuserId: userId,
      touserId: touserId,
      content: comment
   })
   // 根据fromUsreId查询对应的用户名
   let fromUser = await user.findOne({
      where: {
         id: userId
      }
   });

   //根据msgId找到fromUserId
   let msg = await message.findOne({
      where: {
         id: touserId
      }
   });

   //根据找到fromUserId，查找相对应的用户名
   let toUser = await user.findOne({
      where: {
         id: msg.fromuserId
      }
   });

   let data=JSON.parse(JSON.stringify(msg1));


   data.fromUserName = fromUser.username;
   data.toUserName = toUser.username;

   console.log(data);
   console.log(fromUser.username,'kankan');
   console.log(data.fromUserName);

   ctx.body = { code: 200, data, msg: "吐槽成功" };

}

let setting_fn = async (ctx, next) => {

   await ctx.render("setup")
}

let settingDone_fn = async (ctx, next) => {
   let password = ctx.request.body.password;
   let againpassword = ctx.request.body.againpassword;
   console.log(password);
   console.log(againpassword);

   if (password.length > 0 && password === againpassword) {
      let username = ctx.session.username;
      let password = ctx.request.body.password;

      let pa1 = username;
      let password1 = password;


      console.log(password1);
      console.log(pa1)

      await user.update({ password: password1 }, {
         where: {
            username: pa1
         }
      });

      await ctx.redirect("/");


   }
   else {
      ctx.body = "用户名或者密码不能为空 并且两次密码相同";
      console.log("用户名或者密码不能为空 并且两次密码相同")

   }
}

module.exports = {
   "/": ["get", auth, homepage_fn],
   "/login": ["get", auth, login_fn],
   "/register": ["get", register_fn],
   "/loginDone": ["post", loginDone_fn],
   "/registerDone": ["post", registerDone_fn],
   "/logout": ["get", logout_fn],
   "/say": ["post", say_fn],
   "/comment": ["post", comment_fn],
   "/setting": ["get", auth, setting_fn],
   "/settingDone": ["post", settingDone_fn]
}
